package org.zyj.io.example.case3;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.time.LocalDateTime;

/**
 * ChannelHandler生命周期, 执行顺序:
 * ---
 * handlerAdded: handler被添加到channel的pipeline
 * channelRegistered: channel注册到NioEventLoop
 * channelActive: channel准备就绪, 此时可以向channel发送消息
 * channelRead: channel中有可读的数据
 * channelReadComplete: channel读数据完成
 * channelInactive: channel被关闭, 此时不能向channel发送消息
 * channelUnregistered: channel取消和NioEventLoop的绑定
 * handlerRemoved: handler从channel的pipeline中移除
 */
public class ChatServerHandler extends SimpleChannelInboundHandler<String> {

    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        //channel().isActive()是true或false
        Channel channel = ctx.channel();
        //遍历所有channel, 并发送消息
        channelGroup.writeAndFlush("[客户端]" + channel.remoteAddress() + " 加入聊天 " + LocalDateTime.now() + " \n");
        channelGroup.add(channel);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        //channel().isActive()始终为true
        System.out.println(ctx.channel().remoteAddress() + " 上线");
        ctx.channel().writeAndFlush("[自己]" + ctx.channel().remoteAddress() + " 加入聊天 " + LocalDateTime.now() + " \n");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().remoteAddress() + " 离线");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端] " + channel.remoteAddress() + " 离开聊天");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            if (ch != channel) {
                ch.writeAndFlush("[" + channel.remoteAddress() + "]" + "发送了消息: " + msg + "");
            } else {
                ch.writeAndFlush("[自己]" + "发送了消息: " + msg + "");
            }
        });
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
